package com.mijie.homi.common.protocol;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.mijie.homi.common.constant.HomiConstants;
import com.mijie.homi.common.constant.TypeCode;

public class HomiProtocolDecoder extends CumulativeProtocolDecoder {

	private Charset charset;
	
	public HomiProtocolDecoder(Charset charset){
		this.charset = charset;
	}
	
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		
		if(in.prefixedDataAvailable(HomiConstants.PROTOCOL_HEAD_LENGTH, Integer.MAX_VALUE)){
			int packLen = in.getInt();
			short type = in.getShort();
			HomiProtocol protocol = new HomiProtocol(type); 
			if(type>TypeCode.MESSAGE_ROUTER_REPORT){
				fillMessageRouterProtocolContent(protocol,in);
			}else{
				fillGeneralMessageProtocolContent(packLen,protocol,in);
			}
            out.write(protocol); 
            return in.hasRemaining();
		}
		return false;
	}
	
	private void fillGeneralMessageProtocolContent(int packLen,HomiProtocol protocol,IoBuffer in){
		int contentLen = packLen - HomiConstants.PROTOCOL_TYPE_LENGTH;
		if(contentLen<=0) return;
		
		byte[] buff = new byte[contentLen];
        in.get(buff);
        protocol.setContent(new String(buff,charset));
	}
	
	private void fillMessageRouterProtocolContent(HomiProtocol protocol,IoBuffer in){
		int idLen = in.getInt();
		byte[] id = new byte[idLen];
        in.get(id);
        protocol.setId(new String(id,charset));
        
        int contentLen = in.getInt();
        
        byte[] content = new byte[contentLen];
    	in.get(content);
    	protocol.setContent(new String(content,charset));
        
	}

	
}
